package com.chen.giteesso.controller;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.chen.giteesso.entity.GiteeToken;
import com.chen.giteesso.entity.UserInfo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

@Controller
public class GiteeLogin {

    @RequestMapping("/login")
    public String giteeLoginPage(){
        System.out.println("login");
        return "gitee_login";
    }

    @RequestMapping("/index")
    @ResponseBody
    public Map<String,Object> index(String code){
        Map<String,Object> result = new HashMap<>();
        String client_id = "";
        String redirect_uri = "";
        String client_secret = "";

        String resultCode = code;
        if (code == null){
            result.put("code",999);
            return result;
        } else {
            // 发送post请求
            String url = "https://gitee.com/oauth/token";
            Map<String,Object> parms = new HashMap<>();
            parms.put("grant_type","authorization_code");
            parms.put("code",code);
            parms.put("client_id","8ee02c6ffe0d97f6987d1b1110e6879ca06ccc31a553005b12a2a2abfa9058f3");
            parms.put("redirect_uri","http://test.com:8080/index");
            parms.put("client_secret","b7206fd4d855fc9a3b47de0097087b60a2874b363a7fe156ae6189626c3c6d77");
            String access_token = HttpUtil.post(url,parms);

            if (access_token != null){
                JSONObject tokenObject = JSONUtil.parseObj(access_token);
                GiteeToken token = tokenObject.toBean(GiteeToken.class);

                String url2 = "https://gitee.com/api/v5/user?access_token="+token.getAccess_token();
                String infos = HttpUtil.get(url2);


                JSONObject jsonObject = JSONUtil.parseObj(infos);
                UserInfo userInfo = jsonObject.toBean(UserInfo.class);
                result.put("user",userInfo);
                result.put("code",100);
            }
            return  result;
        }
    }
}
//{"access_token":"5b1902fc244c236297cd8a76e9d188a6","token_type":"bearer","expires_in":86400,"refresh_token":"cedc7f3f51422c21dca6aa45f90f92bc34a2b7ad32a104a7c84adc51336882b8","scope":"user_info projects pull_requests issues notes keys hook groups gists","created_at":1538216682}